var req = [];
var CACHETWEETS = 60;

function TweetManager() {
    this.home_max_id = "";	// for home timeline next request
    this.since_id = ["", "", "", ""]; // for mentions, user, favorites; since_id[0] = 'home', not used

    this.home_read_maxid = 0;     // for home unread
    this.mentions_read_maxid = 0; // for mentions unread
    this.inbox_read_latest_id = 0;

    this.home = [];
    this.mentions = [];
    this.inbox = [];

    this.home_unread_cnt = 0;
    this.mentions_unread_cnt = 0;
    this.inbox_unread_cnt = 0;

    this.mine = [];
    this.favorites = [];	// favorites items
    this.sent = [];		// outbox

    this.user_screen_name = "";
    this.user_name = "";
    this.faved = [];
    this.deleted = [];
    this.deleted_dm = [];
    this.currentTabId = 0;
    /* compose data */
    this.isComposing = false;
    this.saveMessage = "";
    this.replyId = null;
    this.retweetId = null;
}

function getCurrentUserInfo() {
    var rnd = new Date().getTime();
    var url = "http://api.t.163.com/account/verify_credentials.json";
    var http = new XMLHttpRequest();
    http.open("GET",
	      url,
	      false);
    http.onload = function() {
	if (http.status != 200) {
	    console.log("get account info failed " + http.status + http.responseText);
	    return;
	}
	var res = eval('(' + http.responseText + ')');
	var instance = TweetManager.instance;
	if (res.screen_name != null)
	    instance.user_screen_name = res.screen_name;
	if (res.name != null)
	    instance.user_name = res.name;
	console.log("account info: " + instance.user_name + " " + instance.user_screen_name);
    }
    http.send(null);
}

function updateNewTwit(id) {
    if (id == 2 && TweetManager.instance.user_screen_name == "") {
	getCurrentUserInfo();
    }

    var names = ["statuses/home_timeline",
		 "statuses/mentions",
		 "statuses/user_timeline/" + TweetManager.instance.user_screen_name,
		 "favorites/" + TweetManager.instance.user_screen_name,
		 "direct_messages",
		 "direct_messages/sent",
		 "reminds/message/latest"
		];

    var TBASE = "http://api.t.163.com/";
    var rnd = new Date().getTime();
    var url = TBASE + names[id] + ".json?";
    if (id == 0) {
	url = url +  "max_id=" + TweetManager.instance.home_max_id + "&rnd=" + rnd;
    } else {
	url = url + "since_id=" + TweetManager.instance.since_id[id] + "&rnd=" + rnd;
    }
    req[id] = new XMLHttpRequest();
    req[id].open("GET",
		 url,
		 true);
    switch (id) {
    case 0:
	req[id].onload = onNewHomeTweets;
	break;
    case 1:
	req[id].onload = onNewMentions;
	break;
    case 2:
	req[id].onload = onNewMine;
	break;
    case 3:
	req[id].onload = onNewFavorites;
	break;
    case 4:
	req[id].onload = onNewInbox;
	break;
    case 5:
	req[id].onload = onNewSent;
	break;
    case 6:
	req[id].onload = onNewMessage;
	break;
    }
    req[id].send(null);
}

function onNewHomeTweets() {
    if (req[0].status != 200) {
	console.log(req[0].status + " " + req[0].responseText);
	return;
    }
    var res = eval('(' + req[0].responseText + ')');
    if (res.length <= 1) {
	return;
    }
    var instance = TweetManager.instance;
    instance.home_max_id = res[0].cursor_id;

    //from old to new, id1>id2 ==> id1 is newer than id2
    for (var i = res.length - 2; i >= 0; i--) {
	instance.home.unshift(res[i]);
	idx = res[i].cursor_id.indexOf(':') + 1
	var time = parseInt(res[i].cursor_id.slice(idx));
	if (time > instance.home_read_maxid) {
	    instance.home_unread_cnt++;
	}
    }
    while (instance.home.length > CACHETWEETS) {
	instance.home.pop();
    }

    var total_unread = instance.home_unread_cnt + instance.mentions_unread_cnt + instance.inbox_unread_cnt;
    if (total_unread > 0)
	chrome.browserAction.setBadgeText({text:String(total_unread)});
}

function onNewMentions() {
    if (req[1].status != 200) {
	console.log(req[1].status);
	return;
    }
    var res = eval('(' + req[1].responseText + ')');
    if (res.length == 0) {
	return;
    }
    var instance = TweetManager.instance;
    instance.mentions = res;
}

function onNewMine() {
    if (req[2].status != 200) {
	console.log(req[2].status + " " + req[2].responseText);
	return;
    }
    var res = eval('(' + req[2].responseText + ')');
    if (res.length == 0) {
	return;
    }
    var instance = TweetManager.instance;
    instance.mine = res;
}

function onNewFavorites() {
    if (req[3].status != 200) {
	console.log(req[3].status + " " + req[3].responseText);
	return;
    }
    var res = eval('(' + req[3].responseText + ')');
    TweetManager.instance.favorites = res;
}

function onNewInbox() {
    if (req[4].status != 200) {
	console.log(req[4].status + " " + req[4].responseText);
	return;
    }
    var res = eval('(' + req[4].responseText + ')');
    if (res.length == 0)
	return;

    var instance = TweetManager.instance;
    instance.inbox = res;
}

function onNewSent() {
    if (req[5].status != 200) {
	console.log(req[5].status + " " + req[5].responseText);
	return;
    }
    var res = eval('(' + req[5].responseText + ')');
    TweetManager.instance.sent = res;
}

function onNewMessage() {
    if (req[6].status != 200) {
	console.log(req[6].status + " " + req[6].responseText);
	return;
    }
    var res = eval('(' + req[6].responseText + ')');
    var instance = TweetManager.instance;
    instance.inbox_unread_cnt = parseInt(res.directMessageCount);
    instance.mentions_unread_cnt = parseInt(res.replyCount);
    if (instance.inbox_unread_cnt > 0) {	// dm
	updateNewTwit(4);
    }
    if (instance.mentions_unread_cnt > 0) {	// mentions
	updateNewTwit(1);
    }
    var total_unread = instance.home_unread_cnt + instance.mentions_unread_cnt + instance.inbox_unread_cnt;
    if (total_unread > 0)
	chrome.browserAction.setBadgeText({text:String(total_unread)});
}

TweetManager.instance = new TweetManager();

function main() {
    console.log("starting main()");
    getCurrentUserInfo();
    console.log("before init, read max_id: " + TweetManager.instance.home_read_maxid, TweetManager.instance.mentions_read_maxid);
    if (localStorage.home_read_maxid != null) {
	TweetManager.instance.home_read_maxid = localStorage.home_read_maxid;
	console.log("read from localStorage home_read_maxid " + TweetManager.instance.home_read_maxid);
    }
    if (localStorage.mentions_read_maxid != null) {
	TweetManager.instance.mentions_read_maxid = localStorage.mentions_read_maxid;
	console.log("read from localStorage mentions_read_maxid" + TweetManager.instance.mentions_read_maxid);
    }
    if (localStorage.inbox_read_latest_id != null) {
	TweetManager.instance.inbox_read_latest_id = localStorage.inbox_read_latest_id;
	console.log("read from localStorage inbox_read_latest_id" + TweetManager.instance.inbox_read_latest_id);
    }
    if (TweetManager.instance.home_read_maxid == null) {
	TweetManager.instance.home_read_maxid = 0;
    }
    if (TweetManager.instance.mentions_read_maxid == null) {
	TweetManager.instance.mentions_read_maxid = 0;
    }
    if (TweetManager.instance.inbox_read_latest_id == null) {
	TweetManager.instance.inbox_read_latest_id = 0;
    }

    var i;
    for (i = 0; i < 7; i++) {
	updateNewTwit(i);
    }
    setInterval(updateNewTwit, 60 * 1000, 0); // home
    setInterval(updateNewTwit, 60 * 1000, 2); // mine
    setInterval(updateNewTwit, 60 * 1000, 3); // fav
    setInterval(updateNewTwit, 60 * 1000, 5); // sent
    setInterval(updateNewTwit, 60 * 1000, 6); // messsage
}
